package com.yztc.love_travel.utils;

import android.content.Context;

import com.yztc.love_travel.bean.WeatherBean;
import com.yztc.love_travel.constant.URLConstant;
import com.yztc.love_travel.helper.weather.NetworkHelper;
import com.yztc.love_travel.helper.weather.httpinterface.HttpCallInterface;
import com.yztc.love_travel.ui.recommondtripnotes.view.IRecommendTripNotesView;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 周旭 on 2016/12/1.
 * "根据城市名获取天气预报的工具类"
 */

public class WeatherUtils {

    private static HttpCallInterface httpCallInterface;

    private Context context;
    private String cityName;
    private IRecommendTripNotesView mRecommendTripNotesView;

    public WeatherUtils(Context context, String cityName,IRecommendTripNotesView mRecommendTripNotesView) {
        this.context = context;
        this.cityName = cityName;
        this.mRecommendTripNotesView = mRecommendTripNotesView;
    }

    /**
     *  获取天气预报结果的Bean
     */
    public void  getWeatherBean() {

        initRetrofit();

        if (!NetworkHelper.isNetworkAvailable(context)) {
            return;
        }
        if (cityName == null) {
            cityName = "北京";
        }
        httpCallInterface.getBeanObservable(cityName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<WeatherBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable error) {
                    }

                    @Override
                    public void onNext(WeatherBean bean) {
                        mRecommendTripNotesView.showWeather(bean);
                    }
                });
    }

    //初始化Retrofit
    private void initRetrofit() {
        OkHttpClient client = OkHttp3Utils.getOkHttpSingletonInstance();
        Retrofit Retrofit = new Retrofit.Builder()
                .baseUrl(URLConstant.URL_BASE)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                // 【特别提示：】Retrofit2+RxJava实现网络访问，必须设置以下选项。
                // RxJavaCallAdapterFactory就是把Call转换成Observable.
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        httpCallInterface = Retrofit.create(HttpCallInterface.class);
    }
}
